#include "data_manager.h"
#include <cstdio> // For sscanf
#include <fstream>
#include <iostream>
#include <sstream>

using namespace std;

// 假设 DATA_FILE 在 data_manager.h 中定义
const char* DATA_FILE = "mastery_data.txt"; // 默认文件路径

// 辅助函数：将 Topics 向量转为字符串，用逗号分隔
string DataManager::topicsToString(const vector<string>& topics)
{
    stringstream ss;
    for (size_t i = 0; i < topics.size(); ++i) {
        ss << topics[i];
        if (i < topics.size() - 1)
            ss << ",";
    }
    return ss.str();
}

// 辅助函数：将逗号分隔的字符串转为 Topics 向量
vector<string> DataManager::stringToTopics(const string& s)
{
    vector<string> topics;
    stringstream ss(s);
    string item;
    // 简单的去除首尾空格，增加健壮性
    size_t start = s.find_first_not_of(" \t\r\n");
    size_t end = s.find_last_not_of(" \t\r\n");
    string trimmed_s = (start == string::npos) ? "" : s.substr(start, end - start + 1);

    stringstream ss_trimmed(trimmed_s);
    while (getline(ss_trimmed, item, ',')) {
        topics.push_back(item);
    }
    return topics;
}

DataManager::DataManager()
{
    loadData();
    // 移除初始化示例数据逻辑，依赖用户提供的初始文件或默认值
    cout << "DataManager initialized. Ready for command input." << endl;
}

void DataManager::saveData()
{
    ofstream outFile(DATA_FILE);
    if (!outFile.is_open()) {
        cerr << "Error: Could not open file for saving." << endl;
        return;
    }

    // 1. 写入 UserConfig - 写入所有配置字段 (新增 OverallMasteryScore)
    outFile << "[CONFIG]\n";
    outFile << "TargetCFRating:" << config.TargetCFRating << "\n";
    outFile << "CurrentCFEquivalent:" << config.CurrentCFEquivalent << "\n";
    outFile << "OverallMasteryScore:" << config.OverallMasteryScore << "\n"; // 新增字段
    // RatingHistory 暂不写入

    // 2. 写入 Problems - 写入所有字段，共 11 个字段
    outFile << "[PROBLEMS:" << problems.size() << "]\n";
    for (const auto& pair : problems) {
        const Problem& p = pair.second;
        // 顺序: ID|Title|Difficulty|Topics|DateSolved|TimeSpentMinutes|UsedSolution|AttemptCount|Omissions|MasteryScore|NextReviewDate
        outFile << p.ProblemID << "|"
                << p.Title << "|"
                << p.Difficulty << "|"
                << topicsToString(p.Topics) << "|"
                << p.DateSolved << "|"
                << p.TimeSpentMinutes << "|"
                << p.UsedSolution << "|" // bool 写入时会被转换为 0 或 1
                << p.AttemptCount << "|"
                << p.Omissions << "|"
                << p.MasteryScore << "|"
                << p.NextReviewDate << "\n";
    }

    // 3. 写入 Topics - 仅写入 4 个字段 (AggregatedMastery 和 TotalSolved 已移除)
    outFile << "[TOPICS:" << topics.size() << "]\n";
    for (const auto& pair : topics) {
        const Topic& t = pair.second;
        // 顺序: Name|Importance|LastReviewed|TopicCFRating (共 4 字段)
        outFile << t.Name << "|"
                << t.Importance << "|"
                << t.LastReviewed << "|"
                << t.TopicCFRating << "\n";
    }

    cout << "Data saved successfully to " << DATA_FILE << "." << endl;
}

void DataManager::loadData()
{
    problems.clear();
    topics.clear();
    ifstream inFile(DATA_FILE);
    if (!inFile.is_open()) {
        return;
    }

    string line;
    string section;
    int count = 0;

    while (getline(inFile, line)) {
        if (line.empty())
            continue;

        if (line == "[CONFIG]") {
            section = "CONFIG";
        } else if (line.rfind("[PROBLEMS:", 0) == 0) {
            section = "PROBLEMS";
            sscanf(line.c_str(), "[PROBLEMS:%d]", &count);
        } else if (line.rfind("[TOPICS:", 0) == 0) {
            section = "TOPICS";
            sscanf(line.c_str(), "[TOPICS:%d]", &count);
        } else if (section == "CONFIG") {
            // 读取 TargetCFRating
            if (line.rfind("TargetCFRating:", 0) == 0) {
                string val = line.substr(line.find(':') + 1);
                config.TargetCFRating = stoi(val);
            }
            // 读取 CurrentCFEquivalent
            else if (line.rfind("CurrentCFEquivalent:", 0) == 0) {
                string val = line.substr(line.find(':') + 1);
                config.CurrentCFEquivalent = stoi(val);
            }
            // 读取 OverallMasteryScore (新增字段)
            else if (line.rfind("OverallMasteryScore:", 0) == 0) {
                string val = line.substr(line.find(':') + 1);
                config.OverallMasteryScore = stof(val);
            }
        } else if (section == "PROBLEMS") {
            stringstream ss(line);
            string segment;
            vector<string> segments;
            // 读取所有 11 个字段
            while (getline(ss, segment, '|')) {
                segments.push_back(segment);
            }

            if (segments.size() >= 11) {
                Problem p;
                p.ProblemID = segments[0];
                p.Title = segments[1];
                p.Difficulty = stoi(segments[2]);
                p.Topics = stringToTopics(segments[3]);
                p.DateSolved = segments[4];
                p.TimeSpentMinutes = stoi(segments[5]);
                // 读取 bool
                p.UsedSolution = (segments[6] == "1" || segments[6] == "true");
                p.AttemptCount = stoi(segments[7]);
                p.Omissions = segments[8];
                p.MasteryScore = stof(segments[9]);
                p.NextReviewDate = segments[10];
                problems[p.ProblemID] = p;
            }
        } else if (section == "TOPICS") {
            stringstream ss(line);
            string segment;
            vector<string> segments;
            // 读取所有 4 个字段 (AggregatedMastery 和 TotalSolved 已移除)
            while (getline(ss, segment, '|')) {
                segments.push_back(segment);
            }

            if (segments.size() >= 4) { // 字段数量从 6 减少到 4
                Topic t;
                t.Name = segments[0];
                t.Importance = stoi(segments[1]);
                // segments[2] 和 segments[3] (AggregatedMastery, TotalSolved) 已移除
                t.LastReviewed = segments[2]; // 对应旧 segments[4]
                t.TopicCFRating = stoi(segments[3]); // 对应旧 segments[5]
                topics[t.Name] = t;
            }
        }
    }

    cout << "Loaded " << problems.size() << " problems and " << topics.size() << " topics." << endl;
}
